<?php

class PluginController extends Controller
{
	private $while_list_ip = array(
      '::1'
   );
   
   private function getRemoteIPAddress(){
      $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
      return $ip;
   }
   /**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
			   'class'=>'CCaptchaAction',
            'backColor'=>0xFFFFFF,
            'transparent'=>true,
            'testLimit'=>1,
            'foreColor'=>0x348017
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
   
   /**
    * HTTP CODE message
   */
   private $http_codes = array(
      100 => 'Continue',
      101 => 'Switching Protocols',
      102 => 'Processing',
      200 => 'OK',
      201 => 'Created',
      202 => 'Accepted',
      203 => 'Non-Authoritative Information',
      204 => 'No Content',
      205 => 'Reset Content',
      206 => 'Partial Content',
      207 => 'Multi-Status',
      300 => 'Multiple Choices',
      301 => 'Moved Permanently',
      302 => 'Found',
      303 => 'See Other',
      304 => 'Not Modified',
      305 => 'Use Proxy',
      306 => 'Switch Proxy',
      307 => 'Temporary Redirect',
      400 => 'Bad Request',
      401 => 'Unauthorized',
      402 => 'Payment Required',
      403 => 'Forbidden',
      404 => 'Not Found',
      405 => 'Method Not Allowed',
      406 => 'Not Acceptable',
      407 => 'Proxy Authentication Required',
      408 => 'Request Timeout',
      409 => 'Conflict',
      410 => 'Gone',
      411 => 'Length Required',
      412 => 'Precondition Failed',
      413 => 'Request Entity Too Large',
      414 => 'Request-URI Too Long',
      415 => 'Unsupported Media Type',
      416 => 'Requested Range Not Satisfiable',
      417 => 'Expectation Failed',
      418 => 'I\'m a teapot',
      422 => 'Unprocessable Entity',
      423 => 'Locked',
      424 => 'Failed Dependency',
      425 => 'Unordered Collection',
      426 => 'Upgrade Required',
      449 => 'Retry With',
      450 => 'Blocked by Windows Parental Controls',
      500 => 'Internal Server Error',
      501 => 'Not Implemented',
      502 => 'Bad Gateway',
      503 => 'Service Unavailable',
      504 => 'Gateway Timeout',
      505 => 'HTTP Version Not Supported',
      506 => 'Variant Also Negotiates',
      507 => 'Insufficient Storage',
      509 => 'Bandwidth Limit Exceeded',
      510 => 'Not Extended'
   );
   
   /**
    * Site partner allow embed comment
   */
   private $sites = array(1 => 'toancanhbaochi.com',2 => 'localhost:2024',3 => 'localhost');
   
   /**
    * Get domain from URL
   */
   public function getDomain($url){
      return parse_url($url, PHP_URL_HOST);
   }
   
   /**
    * Get http respone code
    * @param string url
    * @return int httpcode
   */
   private function getHttpResponeCode($url){
      $handle = curl_init($url);
      curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
      
      /* Get the HTML or whatever is linked in $url. */
      $response = curl_exec($handle);
      
      $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
      curl_close($handle);
      return $httpCode;
   }
   
   /**
    * Get html of any page
    * @param string $url
    * @param second timeout
    * @return data html
   */
   private function getHTML($url,$timeout){
      $ch = curl_init($url); // initialize curl with given url
      curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
      curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
      return curl_exec($ch);
   }
   
   /**
    * Get title of any page
    * @param string url
    * @return string title
   */
   public function getTitle($url){
      $html=$this->getHTML($url,10);
      preg_match("/<title>(.*)<\/title>/i", $html, $match);
      //print_r($match);
      return isset($match[1]) ? $match[1] : "Cannot get title";
   }
   
   /**
    * Form comment
   */
   public function actionComment()
	{
      $model=new Comment;
      $url = Yii::app()->request->getParam('url');
      $model->user_name = isset(Yii::app()->request->cookies['user_name']) ? Yii::app()->request->cookies['user_name'] : '';
      //$site_id = Yii::app()->request->getParam('site_id',0);
      
      $list_comment = array();
      $httpCode = $this->getHttpResponeCode($url);
      if($httpCode == 404){
         Yii::app()->user->setFlash('error','Cannot access url:' . $url . ' <br /> Please try again!');
      }else{
         $domain = $this->getDomain($url);
         if(in_array($domain,$this->sites) || $domain == null){
            $criteria = new CDbCriteria();
            $criteria->addCondition('url= :url');
            $criteria->params = array(':url' => $url);
            $criteria->order = 'id DESC';
            $list_comment = CommentPublish::model()->findAll($criteria);   
         }else{
            Yii::app()->user->setFlash('error','Your domain access denied');
         }
      }
      $this->layout = 'comment';
      
      $this->render('comment',array(
         'model'=>$model,
         'list_comment' => $list_comment,
         'url' => $url,
      ));
      
	}
   
   /**
    * Add comment to database
   */
   public function actionAddComment(){
      $model=new Comment;
      if(isset($_POST['Comment']))
      {
         $model->attributes=$_POST['Comment'];
         $model->verifyCode = $_POST['Comment']['verifyCode'];
         $model->status = 1;
         $model->create_date = date('Y-m-d H:i:s',time());
         $model->url = Yii::app()->request->getParam('url');
         $site_id = Yii::app()->request->getParam('site_id',0);
         if(in_array($site_id,$this->sites)){ // Nếu site_id nằm trong list site cho phép nhúng comment
            $model->site_id = $site_id;
            
            //Lấy news_id từ url
            $regex_id = preg_match('/([0-9]*).htm/i', $model->url, $result);
            $model->news_id = isset($result[1]) ? $result[1] : 0;
            
            //Kiểm tra link còn tồn tại hay không ?
            $httpCode = $this->getHttpResponeCode($model->url);
            if($httpCode != 404){
               $model->page_title = $this->getTitle($model->url);   
               
               //Lấy site_id
               $domain = $this->getDomain($model->url);
               $flip_sites = array_flip($this->sites);
               $model->site_id = $flip_sites[$domain];
               
               //Lấy session captcha hiện tại 
               $client_ip = $this->getRemoteIPAddress();
               if(in_array($client_ip,$this->while_list_ip)){ // Nếu ip nằm trong while_list thì không cần kiểm tra captcha
                  if($model->validate()){
                     $model->save();
                     $error_code = 200;
                     $message = "OK";
                     $cookie = new CHttpCookie('user_name', $model->user_name);
                     $cookie->expire = time()+60*60*24*30; 
                     Yii::app()->request->cookies['user_name'] = $cookie;
                     
                     //Publish comment
                     $published = $this->addCommentPublish($model->id,$model->url,$model->news_id,$model->page_title,$model->site_id,$model->user_name,$model->email,$model->content);
                     
                  }else{
                     $error_code = 500;
                     $message = $model->errors;
                  }
               }else{
                  $captcha=Yii::app()->getController()->createAction("captcha");
                  if($model->verifyCode != $captcha->verifyCode){
                     $model->addError('verifyCode','Mã xác nhận không chính xác');
                     $error_code = 500;
                     $message = $model->errors;
                  }else{
                     if($model->validate()){
                        $model->save();
                        $error_code = 200;
                        $message = "OK";
                        
                        //Publish comment
                        $published = $this->addCommentPublish($model->id,$model->url,$model->news_id,$model->page_title,$model->site_id,$model->user_name,$model->email,$model->content);
                        
                     }else{
                        $error_code = 500;
                        $message = $model->errors;
                     }
                  }
               }
            }else{
               $error_code = $httpCode;
               $message = $this->http_codes[$httpCode];
            }
         }else{
            $error_code = 403;
            $message = 'Your website unregister';
            
         }
         echo json_encode(array('error_code' => $error_code,'message' => $message));
             
      }else{
         echo '<div style="text-align: center;
                           padding: 5px;
                           color: red;
                           border: 1px solid #a10000;">Invalid parameter</div>';
      }
   }
   
   public function addCommentPublish($id,$url,$news_id,$page_title,$site_id,$user_name,$email,$content){
      $model = new CommentPublish();
      $model->id = $id;
      $model->url = $url;
      $model->news_id = $news_id;
      $model->page_title = $page_title;
      $model->site_id = $site_id;
      $model->user_name = $user_name;
      $model->email = $email;
      $model->content = $content;
      $model->create_date = date('Y-m-d H:i:s');
      if($model->validate()){
         return $model->save();   
      }else{
         return $model->errors;
      }
      
   }
   

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}